/**
 * Application 接口定义
 */
export interface Application {
  id: string;
  name: string;
  icon: string; // lucide-react 图标名称
  type: 'internal' | 'iframe' | 'group'; // 应用类型，新增 group 类型
  path: string; // 路由路径或 URL
  children?: Application[]; // 子菜单（用于分组）
}

/**
 * 获取应用列表（模拟数据）
 * 未来可以替换为真实的 API 调用
 */
export async function getApplications(): Promise<Application[]> {
  // 从 API 获取智能体列表
  const agents = await getAgentsForMenu();

  // 返回应用列表数据
  const features = {
    AUTH: import.meta.env?.VITE_FEATURE_AUTH !== 'false',
    CRUD: import.meta.env?.VITE_FEATURE_CRUD !== 'false',
    EXCEL: import.meta.env?.VITE_FEATURE_EXCEL !== 'false',
    GH_TRENDING: import.meta.env?.VITE_FEATURE_GH_TRENDING !== 'false',
    AI: import.meta.env?.VITE_FEATURE_AI !== 'false',
  };

  // 构建工作管理分组
  const workManagementChildren = [
    features.CRUD ? {
      id: 'todo',
      name: '待办事项',
      icon: 'CheckSquare',
      type: 'internal' as const,
      path: '/app/todo',
    } : null,
    features.CRUD ? {
      id: 'notes',
      name: 'Markdown笔记',
      icon: 'FileText',
      type: 'internal' as const,
      path: '/app/notes',
    } : null,
  ].filter(Boolean) as Application[];

  // 构建个人备忘分组
  const personalMemoChildren = [
    features.AI ? {
      id: 'ai-dairy',
      name: 'AI Dairy',
      icon: 'Book',
      type: 'internal' as const,
      path: '/app/ai-dairy',
    } : null,
    features.CRUD ? {
      id: 'contacts',
      name: '通讯录',
      icon: 'Users',
      type: 'internal' as const,
      path: '/app/contacts',
    } : null,
    // 邮件分组
    features.CRUD ? {
      id: 'email-group',
      name: '邮件',
      icon: 'Mail',
      type: 'group' as const,
      path: '#',
      children: [
        {
          id: 'email-viewer',
          name: '邮件查看',
          icon: 'Inbox',
          type: 'internal' as const,
          path: '/app/email-viewer',
        },
        {
          id: 'email-accounts',
          name: '邮箱管理',
          icon: 'Settings',
          type: 'internal' as const,
          path: '/app/email-accounts',
        },
      ],
    } : null,
  ].filter(Boolean) as Application[];

  // 构建开发工具分组
  const devToolsChildren = [
    {
      id: 'json-formatter',
      name: 'JSON格式化',
      icon: 'Code',
      type: 'internal' as const,
      path: '/app/json-formatter',
    },
    features.EXCEL ? {
      id: 'excel-viewer',
      name: 'Excel查看器',
      icon: 'FileSpreadsheet',
      type: 'internal' as const,
      path: '/app/excel-viewer',
    } : null,
    features.GH_TRENDING ? {
      id: 'github-trending',
      name: 'GitHub热门',
      icon: 'Github',
      type: 'internal' as const,
      path: '/app/github-trending',
    } : null,
  ].filter(Boolean) as Application[];

  // 构建AI工具分组
  const aiToolsChildren = [
    features.AI ? {
      id: 'ai-playground',
      name: 'AI Playground',
      icon: 'Sparkles',
      type: 'internal' as const,
      path: '/app/ai-playground',
    } : null,
    // 智能体子分组
    {
      id: 'agents-group',
      name: '智能体',
      icon: 'Bot',
      type: 'group' as const,
      path: '#',
      children: [
        {
          id: 'agent-manager',
          name: '管理智能体',
          icon: 'Settings',
          type: 'internal' as const,
          path: '/app/agents',
        },
        ...agents,
      ],
    },
  ].filter(Boolean) as Application[];

  const apps: Application[] = [
    // 仪表板（置顶，独立）
    {
      id: 'dashboard',
      name: '仪表板',
      icon: 'LayoutDashboard',
      type: 'internal',
      path: '/',
    },
    // 工作管理分组
    workManagementChildren.length > 0 ? {
      id: 'work-management-group',
      name: '工作管理',
      icon: 'Briefcase',
      type: 'group',
      path: '#',
      children: workManagementChildren,
    } : null,
    // 个人备忘分组
    personalMemoChildren.length > 0 ? {
      id: 'personal-memo-group',
      name: '个人备忘',
      icon: 'BookHeart',
      type: 'group',
      path: '#',
      children: personalMemoChildren,
    } : null,
    // 开发工具分组
    devToolsChildren.length > 0 ? {
      id: 'dev-tools-group',
      name: '开发工具',
      icon: 'Wrench',
      type: 'group',
      path: '#',
      children: devToolsChildren,
    } : null,
    // AI工具分组
    aiToolsChildren.length > 0 ? {
      id: 'ai-tools-group',
      name: 'AI工具',
      icon: 'Sparkles',
      type: 'group',
      path: '#',
      children: aiToolsChildren,
    } : null,
    // 系统设置和关于（底部固定）
    features.AUTH ? {
      id: 'settings',
      name: '设置',
      icon: 'Settings',
      type: 'internal',
      path: '/app/settings',
    } : null,
    {
      id: 'about',
      name: '关于',
      icon: 'Info',
      type: 'internal',
      path: '/app/about',
    },
  ].filter(Boolean) as Application[];

  return apps;
}

/**
 * 从 API 获取智能体列表并转换为菜单格式
 */
async function getAgentsForMenu(): Promise<Application[]> {
  try {
    // 使用动态导入避免循环依赖
    const { agentsAPI } = await import('./apiClient');
    const response = await agentsAPI.getAll();
    
    return response.agents.map((agent) => ({
      id: agent.id,
      name: agent.name,
      icon: agent.icon || 'MessageSquare',
      type: 'iframe' as const,
      path: `/app/agent/${agent.id}`,
    }));
  } catch (error) {
    console.error('Failed to load agents for menu:', error);
    return [];
  }
}

